package com.frx.leetoffer.link;

/**
 * Created with IDEA
 *
 * @author: xrf
 * @Date: 2019/10/15
 * @Time: 9:10
 */
public class FindLink {

    public static void main(String[] args){
        Node node = new Node(1);
        Node node1 = new Node(2,node);
        Node node2 = new Node(3,node1);
        Node node3 = new Node(4,node2);
        Node node4 = new Node(5,node3);
        Node node5 = new Node(6,node4);
        nodeToString(node5);
        System.out.println();
        System.out.println(findLink(node5,0));
    }

    public static int findLink(Node head,int k){
        Node fast = head;
        Node slow = head;
        if (k <= 0){
            return 0;
        }
        for (int i=0;i<k;i++){
            fast = fast.next;
        }
        if (fast == null){
            return 0;
        }
        while (fast!=null){
            slow = slow.next;
            fast = fast.next;
        }
        return slow.val;
    }

    public static void nodeToString(Node head){
        while (head.next != null){
            System.out.print( head.val + "->");
            head = head.next;
        }
        System.out.print(head.val);
    }

    private static class Node{
        int val;
        Node next;
        public Node(int val){
            this.val = val;
        }
        public Node(int val,Node next){
            this.val = val;
            this.next = next;
        }
    }
}
